import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:zhibao_flutter/api/commom/common_view_model.dart';
import 'package:zhibao_flutter/api/user/user_entity.dart';
import 'package:zhibao_flutter/api/user/user_view_model.dart';
import 'package:zhibao_flutter/pages/login/login_view.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/config/config_route.dart';
import 'package:zhibao_flutter/util/ui/my_toast.dart';
import 'package:zhibao_flutter/zone.dart';

class LoginInputMajor {
  /// 注册和登录都需要用到
  Rx<LoginType> loginType = LoginType.phone.obs;
  RxString countryCode = AppConfig.countyCodeGet.obs;

  TextEditingController get useAccountController {
    return loginType.value == LoginType.phone
        ? phoneController
        : emailController;
  }

  /// You must use it when commit.
  String get useAccount {
    return loginType.value == LoginType.phone
        ? countryCode.value + phoneController.text
        : emailController.text;
  }

  FocusNode get useAccountFocusNode {
    return loginType.value == LoginType.phone ? phoneFocusNode : emailFocusNode;
  }

  late TextEditingController phoneController;
  late FocusNode phoneFocusNode;
  late TextEditingController emailController;
  late FocusNode emailFocusNode;
  late RxBool loginBtAvalable;
  late TextEditingController pwController;
  late TextEditingController pwAgainController;
}

abstract mixin class LoginInput implements LoginInputMajor {
  /// 注册和登录都需要用到
  @override
  RxString countryCode = AppConfig.countyCodeGet.obs;

  @override
  Rx<LoginType> loginType = LoginType.phone.obs;

  @override
  TextEditingController get useAccountController {
    return loginType.value == LoginType.phone
        ? phoneController
        : emailController;
  }

  /// You must use it when commit.
  @override
  String get useAccount {
    return loginType.value == LoginType.phone
        ? countryCode.value + phoneController.text
        : emailController.text;
  }

  @override
  FocusNode get useAccountFocusNode {
    return loginType.value == LoginType.phone ? phoneFocusNode : emailFocusNode;
  }

  /// 注册和找回密码需要用到========Start
  FocusNode pwAgainFocusNode = FocusNode();
  TextEditingController codeController = TextEditingController();
  TextEditingController inviteController =
      TextEditingController(text: AppConfig.mockInviteCode);
  FocusNode codeFocusNode = FocusNode();
  @override
  TextEditingController pwAgainController =
      TextEditingController(text: AppConfig.mockPw);

  /// 注册和找回密码需要用到========End

  @override
  TextEditingController phoneController =
      TextEditingController(text: AppConfig.mockPhone);
  @override
  FocusNode phoneFocusNode = FocusNode();
  @override
  TextEditingController emailController =
      TextEditingController(text: AppConfig.mockEmail);
  @override
  FocusNode emailFocusNode = FocusNode();
  @override
  TextEditingController pwController =
      TextEditingController(text: AppConfig.mockPw);

  FocusNode pwFocusNode = FocusNode();

  RxBool isFinishPhone = false.obs;
  RxBool isInputPw = false.obs;
  RxBool showPw = false.obs;

  @override
  RxBool loginBtAvalable = false.obs;

  bool registerCheckPassed(bool checkPassWordAgain,
      {bool isPayPassword = false}) {
    if (!loginBtAvalable.value) {
      if (!strNoEmpty(useAccountController.text)) {
        useAccountFocusNode.requestFocus();
        myToast("请填写手机号/邮箱");
      } else if (!strNoEmpty(pwController.text)) {
        pwFocusNode.requestFocus();
        myToast("请填写${isPayPassword ? "交易" : ""}密码");
      } else if (!strNoEmpty(pwAgainController.text)) {
        pwAgainFocusNode.requestFocus();
        myToast("请填写确认${isPayPassword ? "交易" : ""}密码");
      } else if (!strNoEmpty(codeController.text)) {
        codeFocusNode.requestFocus();
        myToast("请填写验证码");
      } else {
        myToast("请填写完整信息");
      }
      return false;
      // } else if (!isMobilePhoneNumber(phoneController.text) &&
      //     !AppConfig.allowAccountNotPhone) {
      //   myToast("请填写正确的手机号/邮箱");
      //   phoneFocusNode.requestFocus();
      //   return false;
    } else if (pwController.text.length < 4) {
      myToast("密码最少输入4位");
      pwFocusNode.requestFocus();
      return false;
    }
    if (checkPassWordAgain) {
      if (pwController.text != pwAgainController.text) {
        myToast("两次${isPayPassword ? "交易" : ""}密码输入不一致");
        pwFocusNode.requestFocus();
        return false;
      }
    }
    return true;
  }

  void onChangePw(String v) {
    isInputPw.value = strNoEmpty(v);
    refreshCommitButton();
  }

  void onChangePhone(String v) {
    isFinishPhone.value = isMobilePhoneNumber(v) || isEmail(v);
    refreshCommitButton();
  }

  void refreshCommitButton();

  Future commit(BuildContext context);
}

class LoginLogic extends GetxController with LoginInput {
  @override
  void onReady() {
    super.onReady();
    refreshCommitButton();
    checkVersion();
  }

  Future checkVersion() async {
    await commonViewModel.checkVersion(Get.context!, false);
  }

  @override
  void refreshCommitButton() {
    LogUtil.d("refreshCommitButton：：");
    loginBtAvalable.value =
        strNoEmpty(useAccountController.text) && strNoEmpty(pwController.text);
  }

  @override
  Future commit(BuildContext context) async {
    if (!registerCheckPassed(false)) {
      return;
    }
    final value = await userViewModel.securityLogin(context,
        username: useAccount, password: pwController.text);
    if (value.data == null) {
      return;
    }
    // userViewModel.loginApiAfter(context, value.data, phoneController);
    if (value.data is Map && (value.data as Map).containsKey("token")) {
      String token = value.data['token'];
      LoginRspEntity loginRspEntity = LoginRspEntity(
          token: token,
          dataCompleted: 1,
          imToken: '',
          sex: 1,
          cityName: '',
          icon: '',
          uid: '',
          iosInCheck: 1,
          androidInCheck: null,
          accountStatus: null,
          accountType: null,
          isVip: 1,
          isConfirmed: 1,
          iosWords: '',
          needConfirm: 12);

      // userViewModel.loginApiAfter(context,loginResult,phoneController.text  );
      userViewModel.loginHandle(
        loginRspEntity,
        useAccount,
      );
    } else {
      myToast('Token异常');
    }
  }

  void toForgetPw() {
    Get.toNamed(RouteConfig.forgetPwPage);
  }

  void toRegister() {
    Get.toNamed(RouteConfig.registerPage);
  }
}
